package git.bankview.wl.console;

import java.io.*;
import java.util.*;
import java.text.*;

import org.apache.log4j.Logger;

public class JournalMonitor
{
	private static Logger log = Logger.getLogger(JournalMonitor.class);
	
	File m_file = null;
	long m_lastModified = 0;
	long m_nPos = 0;
	
	public JournalMonitor(String file)
	{
		log.debug(file);
		m_file = new File(file);
	}
	
	public synchronized String readLine()
	{
		String line = null;
		RandomAccessFile journal = null;
		
		try
		{
			long len = m_file.length();
			if (m_file.exists())
			{
				if(len > m_nPos)
				{
					m_lastModified = m_file.lastModified();
					journal = new RandomAccessFile(m_file, "r");
					journal.seek(m_nPos);
					line = journal.readLine();
					m_nPos = journal.getFilePointer();
				}
				else if (m_file.lastModified() > m_lastModified)
				{
					m_lastModified = m_file.lastModified();
					journal = new RandomAccessFile(m_file, "r");
					line = journal.readLine();
					m_nPos = journal.getFilePointer();
				}
			}
		}
		catch(Throwable e)
		{
			log.info("can not read data from '" + m_file + "'", e);
		}
		finally
		{
			try
			{
				if (null != journal)
					journal.close();
			}
			catch(Throwable e)
			{
				//log.debug("can not close journal file '" + m_file + "'", e);
			}
		}
		
		return line;
	}
}
